from django.http import JsonResponse

from timeholder import models
from django.shortcuts import render, redirect, HttpResponse
from timeholder.forms.project import ProjectModelForm

from datetime import datetime, timedelta
from django.shortcuts import get_object_or_404
from timeholder.models import Task

import json


def project(request):
    """项目列表显示"""
    if request.method == "GET":
        # 查询当前用户的所有项目
        # my_list = models.UserInfo.objects.filter(username=request.user_obj)
        my_list = models.Task.objects.filter(username=request.user_obj.username).order_by('-start_datetime', )[:5]
        # 获得request中保存用户对应的所返回
        task_instance, _ = models.Task.objects.get_or_create(username=request.user.username)
        form = ProjectModelForm(request, instance=task_instance)
        print("project done")
        # 上面form存的是Task对应的表
        # 整合成context传给网页
        context = {
            'form': form,
            'project_dict': my_list
        }
        return render(request, 'project.html', context)
    print("POST done")


def project_add(request):
    print("project add done")
    if request.method == "POST":
        # 传入POST信息
        msg = {
            'username': request.user_obj.username,
            'start_datetime': datetime.now(),
            'end_datetime': datetime.now() + timedelta(minutes=25)  # 固定时间间隔为25分钟
        }
        msg.update(request.POST.dict())
        form = ProjectModelForm(request, data=msg)
        if form.is_valid():
            # 添加项目
            task_instance, _ = models.Task.objects.get_or_create(username=request.user.username)
            form.instance.creator = ProjectModelForm(request, instance=task_instance)
            form.save()
            return JsonResponse({'status': True})
        return JsonResponse({'status': False, 'error': form.errors})


def project_update(request):
    if request.method == "POST":
        data = json.loads(request.body)
        new_data = data.get('new')
        old_data = data.get('old')

        # 原来的数据表单
        task_instance, _ = models.Task.objects.get_or_create(username=request.user_obj.username, name=old_data['name'])

        updateflag = False
        if new_data['text'] != old_data['text']:
            updateflag = True
            task_instance.text = new_data['text']
        if new_data['name'] != old_data['name']:
            updateflag = True
            task_instance.name = new_data['name']

        if updateflag == True:
            try:
                task_instance.start_datetime = datetime.now()
                task_instance.end_datetime = datetime.now() + timedelta(minutes=25)
                task_instance.save()
            except:
                return JsonResponse({'status': False, 'error': 'error'})
        return JsonResponse({'status': True})


def project_delete(request):
    if request.method == "POST":
        msg = {
            'username': request.user_obj.username,
        }
        msg.update(request.POST.dict())
        task_instance = get_object_or_404(Task, username=msg['username'], name=msg['name'])

        # 删除表单项
        task_instance.delete()

    return JsonResponse({'status': True})
